package com.qingmu.club.minaapi.controller.club;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.plus.entity.PushMessage;
import com.qingmu.club.minaapi.plus.entity.UsersWx;
import com.qingmu.club.minaapi.plus.service.PushMessageService;
import com.qingmu.club.minaapi.plus.service.UsersWxService;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@Api(value = "消息推送相关(俱乐部端小程序)", description = "消息推送相关（俱乐部端小程序）")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@RequestMapping("/club/pushMessage")
public class ClubPushMessageController {

    @Autowired
    PushMessageService pushMessageService;

    @Autowired
    UsersWxService usersWxService;

    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "存储推送码")
    public ResponseEntity savePushInfo(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "formId") @RequestParam(required = true) String formId
    ){
        QueryWrapper<UsersWx> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(UsersWx.USER_ID,staffId).eq(UsersWx.TYPE,1);
        UsersWx usersWx = this.usersWxService.getOne(queryWrapper);
        if (usersWx == null){
            return ResponseObject.error(401,"用户不存在");
        }

        String[] strings = formId.split(",");
        for (String str : strings){
            PushMessage pushMessage = new PushMessage();
            pushMessage.setUserId(staffId);
            pushMessage.setOpenId(usersWx.getOpenId());
            pushMessage.setFormId(str);
            pushMessage.setIsUse(false);
            pushMessage.setCreateTime(new Date());
            pushMessage.setType(KeyValueDefine.CLUB_MINI_APP);
            boolean state = this.pushMessageService.save(pushMessage);
            if(!state){
                return ResponseObject.error();
            }
        }

        return ResponseObject.success();

    }

}